package pages;


import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import utils.Log4Test;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: admin
 * Date: 22.05.14
 * Time: 20:01
 * To change this template use File | Settings | File Templates.
 */
public class HomePage {
    private String URL = "http://rozetka.com.ua/";
    protected final By searchString = By.className("header-search-input-text");
    protected final By compareProduct = By.name("tocomparison");
    protected final String productFoundLocator = "//a[contains(text(),'%s')]";
    protected final By productCompare = By.className("g-i-list-compare");
    protected final By comparePageTitle = By.className("title-page");
    protected final By comparePageItems = By.name("topurchases");
    public WebDriver driver;




    public HomePage (WebDriver driver)
    {
        this.driver = driver;
    }

    public void open()
    {
        driver.get(URL);
    }

    public boolean isOpened()
    {
        return driver.getCurrentUrl().equals(URL);
    }

    public boolean searchProduct(String productName)
    {
        WebElement searchField = driver.findElement(searchString);
        Log4Test.info("searching product" + productName);

        searchField.clear();
        searchField.sendKeys(productName);
        searchField.sendKeys(Keys.RETURN);

        return driver.findElement(By.xpath(String.format(productFoundLocator,productName))).isDisplayed();
    }

    public void addProductToComparison()
    {
        driver.findElement(compareProduct).click();
    }

    public void goToComparisonPage()
    {
        Log4Test.info("Going to comparison page");
        WebElement productCompareBlock = driver.findElement(productCompare);

//        WebDriverWait wait = new WebDriverWait(driver, 40);
//        wait.until(ExpectedConditions.vi(By.className()));
        productCompareBlock.findElement(By.tagName("a")).click();
    }

    public String getComparePageTitle()
    {
        return driver.findElement(comparePageTitle).findElement(By.tagName("h1")).getText();
    }

    public int getCompareItems()
    {
        return driver.findElements(comparePageItems).size();
    }

    public void waitForLoad() {
        driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
    }
}
